﻿using dotnet_graphql_demo.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace dotnet_graphql_demo.Infrastructure
{
    public class AccountRepository : IAccountRepository,IAsyncDisposable
    {
        private readonly AppDbContext appDbContext;

        public AccountRepository(IDbContextFactory<AppDbContext> dbContextFactory)
        {
            appDbContext = dbContextFactory.CreateDbContext();
        }


        /// <summary>
        /// 获取所有账户
        /// </summary>
        /// <returns></returns>
        public async Task<List<Account>> GetAccountsAllAsync()
        {
            return await appDbContext.Accounts.AsNoTracking().ToListAsync();
        }

        /// <summary>
        /// 获取账号详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Task<Account> GetAccountAsync(Guid id)
        {
            return appDbContext.Accounts.Where((c) => c.Id == id).FirstOrDefaultAsync();
        }

        /// <summary>
        /// 创建账号
        /// </summary>
        /// <param name="account"></param>
        public async Task<Account> CreateAccountAsync(Account account)
        {
            appDbContext.Accounts.Add(account);
            await appDbContext.SaveChangesAsync();
            return account;
        }

        /// <summary>
        /// 通过id获取账号
        /// </summary>
        /// <param name="OwnerId"></param>
        /// <returns></returns>
        public Task<List<Account>> GetAccountsByOwnerIdAsync(Guid OwnerId)
        {
            return appDbContext.Accounts.AsNoTracking().Where((c) => c.OwnerId == OwnerId).ToListAsync();
        }

        /// <summary>
        /// 修改账号
        /// </summary>
        /// <param name="dbAccount"></param>
        /// <param name="account"></param>
        public async Task<Account> UpdateAccountAsync(Account dbAccount)
        {
            appDbContext.Accounts.Update(dbAccount);
            await appDbContext.SaveChangesAsync();
            return dbAccount;
        }

        /// <summary>
        /// 删除账号 
        /// </summary>
        /// <param name="account"></param>
        public async Task<Account> DeleteAccountAsync(Account account)
        {
            appDbContext.Accounts.Remove(account);
            await appDbContext.SaveChangesAsync();
            return account;
        }

        public ValueTask DisposeAsync()
        {
            return appDbContext.DisposeAsync();
        }
    }
}
